<template>
  <div class="login-modal">
    <div class="mask"></div>
    <div class="login-box">
      <div>
        <img
          src="../assets/img/close.png"
          alt=""
          class="close"
          @click="close"
        />
      </div>
      <ul class="title">
        <li :class="isShowForm ? 'active' : ''" @click="chanIsShowForm(true)">
          手机号码登录
        </li>
        <li style="margin: -3px 10px 0" cursor="auto">|</li>
        <li :class="!isShowForm ? 'active' : ''" @click="toshowWeixin">
          微信扫码登录
        </li>
      </ul>
      <div class="modal_body">
        <div class="form" v-show="isShowForm">
          <div class="input_group">
            <input
              type="text"
              placeholder="请输入手机号"
              v-model="phoneNum"
              ref="phone"
            />
          </div>
          <div>
            <slide-verify
              :l="42"
              :r="20"
              :w="362"
              :h="140"
              @success="onSuccess"
              @fail="onFail"
              @refresh="onRefresh"
              :style="{ width: '100%', margin: '0 0 20px' }"
              class="slide-box"
              ref="slideBlock"
              :slider-text="msg"
            ></slide-verify>
          </div>
          <div class="input_group code">
            <input
              type="text"
              placeholder="请输入短信验证码"
              v-model="SMScode"
            />
            <div class="btn" :style="{ background: isShowCount ? '#ccc' : '' }">
              <span v-show="!isShowCount" @click="getSMScode">获取验证码</span>
              <span v-show="isShowCount">{{ downNum }} s</span>
            </div>
          </div>
          <div class="btn" @click="sunbmitLogin">登录</div>
        </div>
        <div class="wx-qrcode" v-show="!isShowForm" id="weixin"></div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from "vuex";
import { validatePhoneNumber } from "@/utils";
import { SMScodeAPI, PhoneLoginAPI, BindphoneAPI, UserProfilesAPI } from "../request/api"; // 引入接口文件

export default {
  data() {
    return {
      // 图片验证码滑动文字
      msg: "向右滑动",
      // 用户输入的手机号
      phoneNum: "",
      // 倒计时的数字
      downNum: 60,
      // 控制倒计时的显示和隐藏
      isShowCount: false,
      // 获取验证码
      SMScode: "",
    };
  },
  computed: {
    ...mapState({
      // 控制登录状态的值
      islogined: (state) => state.Loginstatus.islogined,
      // 控制表单盒子的显示和隐藏
      isShowForm: (state) => state.ShowForm.isShowForm,
    }),
  },
  created() {
      // 获取二维码
      // 微信登录第一步：申请微信登录二维码
      // this.$nextTick(() => {}  获取挂载之后的数据
      this.$nextTick(() => {
        let _this = this;
        new WxLogin({
          id: "weixin",
          appid: "wx67cfaf9e3ad31a0d", // 这个appid要填死
          scope: "snsapi_login",
          // 扫码成功后重定向的接口
          redirect_uri: "https://sc.wolfcode.cn/cms/wechatUsers/shop/PC",
          // state填写编码后的url
          state: encodeURIComponent(
            window.btoa("http://127.0.0.1:8080" + _this.$route.path)
          ),
          // 调用样式文件
          href: "data:text/css;base64,Lyogd3hsb2dpbi5jc3MgKi8NCi5pbXBvd2VyQm94IC50aXRsZSwgLmltcG93ZXJCb3ggLmluZm97DQogIGRpc3BsYXk6IG5vbmU7DQp9DQoNCi5pbXBvd2VyQm94IC5xcmNvZGV7DQogIG1hcmdpbi10b3A6IDIwcHg7DQp9",
        });
      });
    },
  methods: {
    ...mapMutations({
      chanisShowLoginModal: "ShowLoginModal/chanisShowLoginModal",
      chanIslogined: "Loginstatus/chanIslogined",
      chanIsShowForm: "ShowForm/chanIsShowForm",
    }),
    ...mapActions({
      asyncchanToShowtoast: "ShowToast/asyncchanToShowtoast",
      asyncChanUserInfo: "UserInfo/asyncChanUserInfo",
    }),
    toshowWeixin() {
      // 切换到展示二维码的界面
      this.chanIsShowForm(false);
    },
    // 关闭登录窗口
    close() {
      // 点击模态窗口，关闭模态框，本质上是修改state里面的isShowLoginModal的值为false
      this.chanisShowLoginModal(false);
      this.asyncchanToShowtoast({
        msg: "登录失败",
        type: "danger",
      });
    },
    // 拼图成功
    onSuccess(times) {
      let ms = (times / 1000).toFixed(1);
      this.msg = "login success, 耗时 " + ms + "s";
    },
    // 拼图失败
    onFail() {
      this.onRefresh(); // 重新刷新拼图
    },
    // 拼图刷新
    onRefresh() {
      this.msg = "再试一次";
    },

    // 倒计时
    countDowm() {
      let timer = setInterval(() => {
        this.downNum--;
        // 如果数字到0，清除定时器，显示文本，倒计时数字还原
        if (this.downNum === 0) {
          clearInterval(timer);
          this.isShowCount = true;
          this.downNum = 60;
        }
      }, 1000);
    },
    // 验证手机号码和滑块拼图 的函数封装
    verifyFn() {
      // 1 验证用户输入的手机号码格式是否正确，如果不正确，就return
      // if(!正则对象.test(用户输入的信息)){}
      if (!validatePhoneNumber(this.phoneNum)) {
        this.asyncchanToShowtoast({
          msg: "请输入正确的手机号码",
          type: "danger",
        });
        this.$refs.phone.focus();
        return false;
      }
      // 2 验证滑块拼图验证码，如果不通过就return
      if (this.msg === "再试一次" || this.msg === "向右滑动") {
        this.asyncchanToShowtoast({
          msg: "请滑动滑块至正确位置！",
          type: "danger",
        });
        return false;
      }
      return true;
    },
    // 短信验证码验证
    async getSMScode() {
      // 1 验证用户输入的手机号码格式是否正确，如果不正确，就return

      if (!this.verifyFn()) {
        return true;
      }
      // 3 发短信验证码----就是一个请求,显示倒计时
      // res 接收响应后return的值
      let res = await SMScodeAPI({
        phone: this.phoneNum.trim(),
      });
      // 响应成功，执行这里的代码
      if (res) {
        this.asyncchanToShowtoast({
          msg: "验证码已发送至手机上，请注意查收",
          type: "success",
        });
        // 调用倒计时方法
        this.countDowm();
        // 显示倒计时
        this.isShowCount = true;
      }
    },
    // 登录验证
    async sunbmitLogin() {
      // 1 手机号码的验证
      // 2 图片滑块验证码的验证
      if (!this.verifyFn()) {
        return true;
      }
      // 3 验证用户输入的验证码是否为空，为空就return
      if (!this.SMScode.trim()) {
        this.asyncchanToShowtoast({
          msg: "请输入短信验证码",
          type: "warnimg",
        });
        return;
      }
      // 通过验证，发起验证请求
      // 登录要根据有没有uuid的情况，发送对应的请求
      let uuid = localStorage.getItem("uuid");
      let res = null;
      if (uuid) {
        res = await BindphoneAPI({
          phone: this.phoneNum.trim(),
          verifyCode: this.SMScode.trim(),
          uuid,
        });
      } else {
        res = await PhoneLoginAPI({
          // 通过验证，发起登录请求
          phone: this.phoneNum.trim(),
          verifyCode: this.SMScode.trim(),
        });
      }

      if (res) {
        console.log(res);
        // 登录成功后的操作
        // 1 提示用户登录成功
        this.asyncchanToShowtoast({
          msg: "登录成功",
          type: "success",
        });
        // 2 关闭登录窗口
        this.chanisShowLoginModal(false);
        // 3 保存token值到localStorage中
        localStorage.setItem("x-auth-token", res["x-auth-token"]);
        // 4 登录状态的切换（隐藏登录按钮展示购物车按钮，用户昵称头像）
        this.chanIslogined(true);

        // 5 删除uuid，并且清除浏览器地址上面的code
        if (uuid) {
          localStorage.removeItem("uuid");
          // 清除浏览器地址栏上面的code
          this.$router.push(this.$route.path);
        }
        // 发送请求获取用户信息
        this.asyncChanUserInfo()
      }
    },
  },
};
</script>
 
<style lang = "less" scoped>
@import "../assets/css/global.less";
.login-modal {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  .mask {
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.3);
  }
  .login-box {
    width: 555px;
    height: 423px;
    background: url("../assets/img/login-box-bg.png");
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    .close {
      position: absolute;
      right: 60px;
      top: 15px;
      cursor: pointer;
    }
    .title {
      display: flex;
      justify-content: center;
      padding: 40px 0 30px;
      font-size: 18px;
      color: #ccc;
      cursor: pointer;
      .active {
        color: #333;
      }
    }
    .modal_body {
      width: 360px;
      margin: auto;
      .form {
        .btn {
          height: 50px;
          line-height: 50px;
          background-color: @basecolor;
          color: #fff;
          text-align: center;
        }
        .input_group {
          display: flex;
          justify-content: space-between;
          margin-bottom: 20px;
          input {
            width: 100%;
            height: 46px;
            text-indent: 10px;
            border: 1px solid #eee;
          }
        }
        .code {
          input {
            width: 260px;
          }
          .btn {
            width: 80px;
          }
        }
      }
    }
  }
}

/deep/.slide-box {
  width: 100%;
  position: relative;
  box-sizing: border-box;
  canvas {
    position: absolute;
    left: 0;
    top: -120px;
    display: none;
    width: 100%;
    box-sizing: border-box;
  }
  .slide-verify-block {
    width: 85px;
    height: 136px;
  }
  .slide-verify-refresh-icon {
    top: -120px;
    display: none;
  }
  &:hover {
    canvas {
      display: block;
    }
    .slide-verify-refresh-icon {
      display: block;
    }
  }
}
/* 微信二维码样式 */
#weixin {
  /* background-color: #fcf; */
  display: flex;
  justify-content: center;
  margin-top: -20px;
}
</style>